<?php
namespace app\common\controller;
use think\Controller;
use think\Db;
use think\cache\driver\Redis;
use app\common\logic\JsksPayment;

class JsksAll extends Controller {
    protected $czid;
    protected $time;
    protected $redis;
    
    public function _initialize() {
        parent::_initialize();
        set_time_limit(0);
        $this->czid = '72';
        $this->time = time();
        $this->redis = new Redis();
    }
    /************************************开奖****************************************************/
	
	//统计大小单双
	static private function getCurrentResult($qihao,$czid=72){
		
        $list = Db::name("touzhu_list_no")->field("tzhm,tzje")->where(['czid'=>$czid,'qihao'=>$qihao])->where('tzhm','in',['单','双','大','小'])->select();
        $ret = ['single'=>0,'double'=>0,'big'=>0,'small'=>0];
        foreach($list as $v){
            if( '单'==$v['tzhm'] ) $ret['single']+=$v['tzje'];
            if( '双'==$v['tzhm'] ) $ret['double']+=$v['tzje'];
            if( '大'==$v['tzhm'] ) $ret['big']+=$v['tzje'];
            if( '小'==$v['tzhm'] ) $ret['small']+=$v['tzje'];
        }
        return $ret;
    }
	 /**
     * 开奖结果计算
     */
    public function kj_index() {
		$big =1;   //大
		$small = 2; //小
		$single =3;    //单
		$double =4;    //双
		$kjj = '';
		$dig_small ='';
		
		
		//获取最新应开奖期号
        $info = Db::name('kjjg_list')->where(['czid'=>$this->czid,'kjjg'=>'0'])->field('qihao,jztime')->where('jztime','<',$this->time)->order('id','DESC')->find();
   
	   $qihao =$info['qihao'];  
		
		$aa = self:: getCurrentResult($qihao);//Array ( [single] => 2.2 [double] => 0.2 [big] => 0.2 [small] => 2.2 );
		//print_r($aa);
			$single = $aa['single'];
			$double = $aa['double'];
			$big = $aa['big'];
			$small = $aa['small'];
			$num_01 ='';
			
			if($single+$double+$big+$small>0){
				
				($big>$small)? $dig_small=2:$dig_small=1;
				($single>$double)? $sin_dou=4: $sin_dou=3;
				
				$arr = $this->res($dig_small,$sin_dou);
				
				for($i=0;$i<3;$i++){
				 $kjj .=  $arr[$i];
					
				}
			}else{
				for($i=0;$i<3;$i++) $kjj .=  mt_rand(1,6);
			}
		
		return   $kjj ; 
	
	
	}
	//大小单双
	public function res($size,$dans){
		//开奖状态：大（11-18），小（3-10），单（和值不能被2整除），双（和值能被2整除）
		$xiao_dan=array(3,5,7,9);
		$xiao_sh=array(4,6,8,10);
		$big_dan=array(11,13,15,17);
		$big_sh=array(12,14,16,18);
		$arr_num=array();
    //小单
	if($size==2 && $dans==3){		
       $num=array_rand($xiao_dan,1);
	   
	    $max= $xiao_dan[$num];
		if( $max==3){
			$arr_num=array(1,1,1);
		}else{
			
			$arr_num1 =  $this->rand_num($max-2);
			$arr_num2 =  $this->rand_num($max-$arr_num1-1); 
			$arr_num3 = $max-$arr_num1-$arr_num2 ;			
			$arr_num[0] = $arr_num1;
			$arr_num[1] = $arr_num2;
			$arr_num[2] = $arr_num3;
		}
		//echo '小单';
	}
	
	    //小双
	if($size==2 && $dans==4){

        $num=array_rand($xiao_sh,1);
	    $max= $xiao_sh[$num];
		$arr_num1 =  $this->rand_num($max-2);
		$arr_num2 =  $this->rand_num($max - $arr_num1-1); 
		$arr_num3 = $max-$arr_num1-$arr_num2 ;	
		$arr_num[0] = $arr_num1;
		$arr_num[1] = $arr_num2;
		$arr_num[2] = $arr_num3;
		//echo '小双';
	}
	
	  //大单
	if($size==1 && $dans==3){		
       $num=array_rand($big_dan,1);
	    $max= $big_dan[$num];
	   
		$arr_num1 =  $this->rand_num(6);
		$arr_num2 =  $this->rand_num($max - $arr_num1-1); 
		$arr_num3 = $max-$arr_num1-$arr_num2 ;	
		if($arr_num3>6){
			$arr_num1=6;
			$arr_num2=ceil(($max-6)/2);
			$arr_num3 = $max-$arr_num1-$arr_num2 ;	
		}
		$arr_num[0] = $arr_num1;
		$arr_num[1] = $arr_num2;
		$arr_num[2] = $arr_num3;
		//echo '大单';
	}
	
	  //大双
	if($size==1 && $dans==4){		
       $num=array_rand($big_sh,1);
	    $max= $big_sh[$num];
		
		$arr_num1 =  $this->rand_num(6);
		$arr_num2 =  $this->rand_num($max - $arr_num1-1); 
		$arr_num3 = $max-$arr_num1-$arr_num2 ;	
		if($arr_num3>6){
			$arr_num1=6;
			$arr_num2=ceil(($max-6)/2);
			$arr_num3 = $max-$arr_num1-$arr_num2 ;	
		}
		$arr_num[0] = $arr_num1;
		$arr_num[1] = $arr_num2;
		$arr_num[2] = $arr_num3;
		//echo '大双';
	}
	
	return $arr_num;

}

public function rand_num($max){
	if($max<1){$max=1;}
	if($max>6){	$max=6;	}	
    $num= mt_rand(1,$max);
 return   $num;
}

/************************************开奖   EEE ****************************************************/ 

	
    /**
     * 获取开奖数据并执行后续操作
     */
    public function index() {
		
		//查看过滤是否开启
	    $info = Db::name('caipai_list')->where(['id'=>$this->czid])->field('filter')->find();
		if(0==$info['filter']){
			$kjj ='';
			for($i=0;$i<3;$i++) $kjj .=  mt_rand(1,6);
		}else{
			$kjj = $this->kj_index();
		}
		echo $kjj;

        echo "---------- 开始处理当期数据 ----------<br/><br/>";
       
        //随机生成开奖号码
        //for($i=0;$i<3;$i++) $kjj .=  mt_rand(1,6);
		
        //获取最新应开奖期号
        $info = Db::name('kjjg_list')->where(['czid'=>$this->czid,'kjjg'=>'0'])->field('qihao,jztime')->where('jztime','<',$this->time)->order('id','DESC')->find();
        $que = Db::name('caipiao')->where(['czid'=>$this->czid,'qihao'=>$info['qihao']])->find();
        if($que){
        	$kjj = explode(',', $que['kjjg']);
        	$kjj = implode('', $kjj);
        }
        $timestamp = strtotime(date('Y-m-d H:i',$this->time).':00');
        $in = Db::name('time')->where(['czid'=>$this->czid,'jztime'=>date('H:i:s',$timestamp)])->order('id','DESC')->field('qihao')->find();
        if(strlen($in['qihao'])==1){$in['qihao'] = '000'.$in['qihao'];}
        if(strlen($in['qihao'])==2){$in['qihao'] = '00'.$in['qihao'];}
        if(strlen($in['qihao'])==3){$in['qihao'] = '0'.$in['qihao'];}
        //无数据情况补足
        if(!$info) {
        	if($in['qihao']==1440 && $in['jztime']='00:00:00') {
        		$info['qihao'] = date('Y-m-d',strtotime('-1 day')).$in['qihao'];
        	}else{
        		$info['qihao'] = date('Ymd').$in['qihao'];
        	}
            $info['jztime'] = $timestamp;
        }
		
        //---------------------最后删除-----------------------------//

        //---------------------最后删除----------------------------//
        $result = array(
                'qihao' => $info['qihao'],
                'czid' => $this->czid,
                'opencode' => $kjj,
                'pentime' => date('Y-m-d H:i:s',$this->time),
                'opentimestamp' => $this->time,
        );
        
        $result_json = json_encode($result);
        $this->insertDataRedis($result_json);
        
        //开奖结果入库
        $this->kjjgSave($this->czid,$info['qihao'],$info['jztime'],$kjj);
        //将最新开奖数据存入Redis
        $this->redis->set("result_{$this->czid}","{$info['qihao']},{$info['jztime']},{$kjj}");
        
        echo "<br/>---------- 处理当期数据完成 ----------<br/>";
        
        //生成新期数据
        $this->processingNew($info['qihao']);
        usleep(10000);
        //中奖结算
        $this->payment();
    }
    
    

    /**
     * 执行开奖数据入库操作
     */
    private function kjjgSave($czid,$qihao,$jztime,$kjjg_string) {
        // 查询是否存在本期
        $exist = Db::name('kjjg_list')->where(['qihao'=>$qihao,'czid'=>$czid])->find();
        
        if($exist) {
            if(!$exist['iftz']) {
                Db::name('kjjg_list')->where('id',$exist['id'])->data(['kjjg'=>$kjjg_string,'iftz'=>1])->update();
                echo "{$czid} 号彩第 {$qihao} 期数据更新成功<br/>";
            }
            } else {
            Db::name('kjjg_list')->data(['czid'=>$czid,'qihao'=>$qihao,'jztime'=>$jztime,'kjjg'=>$kjjg_string,'iftz'=>1])->insert();
            echo "{$czid} 号彩第 {$qihao} 期数据写入成功<br/>";
            }
    }
    
    /**
     * 生成新期数据
     */
    private function processingNew($last_qihao) {
    	/* try{
    		Db::execute("CREATE TABLE `kkty_kjjg".date('Ymd')."` (
	               `id` int(11) unsigned NOT NULL AUTO_INCREMENT,`czid` smallint(6) unsigned NOT NULL DEFAULT '0' COMMENT '彩种ID',`qihao` varchar(15) NOT NULL DEFAULT '' COMMENT '期号',`jztime` varchar(100) NOT NULL COMMENT '截止投注时间',`kjjg` varchar(150) NOT NULL DEFAULT '' COMMENT '开奖结果',`iftz` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否投注 0为正常投注，1为禁止投注 2为已退款',
	               `ps` varchar(100) NOT NULL DEFAULT '官方彩无预设' COMMENT '预设结果',`rktime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',PRIMARY KEY (`id`),
	               KEY `order` (`id`,`czid`,`jztime`)) ENGINE=InnoDB AUTO_INCREMENT=1032215 DEFAULT CHARSET=utf8");
			echo '创建表成功';
    	}catch (\Exception $e){
    		echo "创建表失败";
    	} */
        echo "<br/>---------- 开始生成下期数据 ----------<br/><br/>";
        $data = Db::name('time')
        			->alias('t')
        			->join('__CAIPAI_LIST__ cl','cl.id=t.czid')
        			->field('t.*,cl.cp_fp_time')
        			->where('t.czid',$this->czid)->where('t.jztime','>=',date('H:i:s',$this->time))->order('t.id','ASC')->find();
        
        if(strlen($data['qihao'])==1){$data['qihao'] = '000'.$data['qihao'];}
        if(strlen($data['qihao'])==2){$data['qihao'] = '00'.$data['qihao'];}
        if(strlen($data['qihao'])==3){$data['qihao'] = '0'.$data['qihao'];}
        //极速PK10
        
        $sz_time = strtotime(date('Y-m-d').$data['jztime']);

       if(empty($data)){
       		$qihao = date('Ymd').'1440';
       		$sz_time = strtotime(date('Y-m-d ',strtotime('+1 day')).'00:00:00' );
       }else{
        	$qihao = date('Ymd').$data['qihao'];
       }
        $sz_time = floor($sz_time)-floor($data['cp_fp_time']);
        $this->insertNew($this->czid,$qihao,$sz_time,'');
        
        //将当期期号存入redis，生成新期后此期便作为上一期，便于后续操作
        $this->redis->set("secend_{$this->czid}","{$last_qihao}");

        //检查新期是否存在追号
        $trace_num = Db::name('touzhu_list_zh')->where(['czid'=>$this->czid,'qihao'=>['<=',$qihao]])->select();
        if($trace_num) {
            foreach($trace_num as $vt) {
                $data = array(
                	'czid' => $vt['czid'],'qihao' => $vt['qihao'],'tzhm' => $vt['tzhm'],'tzje' => $vt['tzje'],'dzje' => $vt['dzje'],
                    'tzzs' => $vt['tzzs'],'username' => $vt['username'],'tzhje' => $vt['tzhje'],'zjje'  => $vt['zjje'],
                    'ifqs' => $vt['ifqs'],'wfid' => $vt['wfid'],'dqpl' => $vt['dqpl'],'xzfd' => $vt['xzfd'],'fdje' => $vt['fdje'],
                    'kjjg' => $vt['kjjg'],'zjzs' => $vt['zjzs'],'nbzh' => $vt['nbzh'],'tz_time' => $vt['tz_time'],'method'=> $vt['method']
                );
                $data['from'] = 1==intval($vt['stop']) ? 1 : 2;
                Db::startTrans();
                try {
                    Db::name('touzhu_list_no')->data($data)->insert();
                    Db::name('touzhu_list_zh')->data($data)->where('id',$vt['id'])->delete();
                    Db::commit();
                    echo "{$vt['czid']} 号彩第 {$qihao} 期追号更新成功<br/>";
                } catch (\Exception $e) {
                    Db::rollback();
                    echo "{$vt['czid']} 号彩第 {$qihao} 期追号更新失败<br/>";
                }
                usleep(10000);
            }
        }

        echo "<br/>---------- 生成下期数据完成 ----------";
    }

    /**
     * 新期写入库
     */
    private function insertNew($czid,$qihao,$jztime,$pss) {
        $res = Db::name('kjjg_list')->where(['czid'=>$czid,'qihao'=>$qihao])->find();
        if(!$res) {
            Db::name('kjjg_list')->data(['czid'=>$czid,'qihao'=>$qihao,'jztime'=>$jztime,'kjjg'=>'0','iftz'=>0,'ps'=>$pss])->insert();
            echo "{$czid} 号彩第 {$qihao} 期新期写入成功";
            $this->insertNewRedis($czid,$qihao,$jztime);
        }
    }

    /**
     * 新期写入Redis
     */
    private function insertNewRedis($czid,$qihao,$jztime) {
        $this->redis->set("{$czid}","{$qihao},{$jztime},0");
        echo " Redis写入成功<br/>";
    }
    
    /**
     * 最新开奖数据写入Redis
     */
    private function insertDataRedis($data) {
        $this->redis->set('Jsks_kjjg',"{$data}");
        @file_put_contents('./jskslog/newdata/'.date('Ymd',$this->time).'.txt',$data."\n",FILE_APPEND);
    }
    
    /**
     * 开奖结算
     */
    private function payment() {
        
        echo "<br/><br/>---------- 开始处理结算统计 ----------<br/>";
        $ctime = microtime(true);
        $cur_time = time();
        //非关联方式，循环查询
        /* $data_all = Db::name('touzhu_list_no')->alias('t')
                            ->join('__USERNAME__ u','t.username=u.username')
                            ->field('t.*,u.id as user_id,u.swzh,u.nbzh as nb')
                            ->where('t.czid','62')
                            ->limit(1000)
                            ->select(); */
        //关联方式，但因为开奖表数据量大，效率待定，具体说明参看logic->FfcPayment
        $data_all = Db::name('touzhu_list_no')->alias('t')
                            ->join('__KJJG_LIST__ k','t.czid=k.czid and t.qihao=k.qihao')
                            ->join('__USERNAME__ u','t.username=u.username')
                            ->field('t.*,k.kjjg,u.id as user_id,u.swzh,u.nbzh as nb')   //k.kjjg务必放在t.*之后
                            ->where('k.kjjg','<>','0')
                            ->where('t.czid','72')
                            ->limit(1000)
                            ->select();
        
        $count = count($data_all);
        foreach($data_all as $v) {
        	
                $ffc = JsksPayment::getInstance();
                $payment_result = $ffc->dealInfo($v);
                if($payment_result !== false) {
                    $this->sendMessage($v['username'],'极速快三','极速快三',$v['qihao'],$payment_result);
                }
        }
        $time = microtime(true)-$ctime;
        $ymd = date('Y-m-d H:i:s',$cur_time);
        @file_put_contents('./jskslog/payment/'.date('Ymd',$cur_time).'.txt',"{$ymd}，用时{$time}s，可处理{$count}条\n",FILE_APPEND);
        echo "<br/>{$time}，{$count}<br/>";
        echo "<br/>---------- 结算统计处理完成 ----------<br/>";
    }
    
    /**
     * 会员消息发送
     */
    private function sendMessage($username,$cp_name_old,$cp_name_new,$qihao,$zjje) {
        if(!$cp_name_new) $cp_name_new = $cp_name_old;
        $message = "您投注的:【{$cp_name_new}】，【{$qihao}】期已开奖，中奖金额:【{$zjje}】元！";
        $data = array(
                'username' => $username,
                'test' =>$message ,
                'xx_time' => $this->time,
                'ifdq' => 0
        );
        Db::name('xiaoxi')->data($data)->insert();
    }
}
